<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\AccountCate;
use think\App;

use app\common\builder\TableBuilder;
use app\common\builder\TableFront;
use think\response\Json;

class BonusPoolRecord extends Base
{

    //主键，默认为id
    protected $pk = 'id';

    //主模型
    protected $model = '\app\common\model\BonusPoolRecord';

    protected $sort = 'id,desc';

    protected $append = ['type_text'];

    protected $hasOne = ['orders'];

    //入池记录
    public function index()
    {
        return $this->setTable('index');
    }

    public function setTable($action, $extra_map = [])
    {
        //构建table
        $tableFront = TableFront::getInstance()
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addRow(['field' => 'type_text', 'title' => '类型'])
            ->addRow(['field' => 'create_time', 'title' => '创建时间'])
            ->addRow(['field' => 'total_profit', 'title' => '订单总利润'])
            ->addRow(['field' => 'profit_rate', 'title' => '利润比例'])
            ->addRow(['field' => 'amount', 'title' => '分红金额'])
            ->addRow(['field' => 'order_sn', 'title' => '来源订单号', 'templet' => '<span>{{d.orders?d.orders.sn:""}}</span>']);

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->setSearch($this->setSearch($action))
            ->addExtraMap($extra_map)
            ->addTopButtons(['export'])
            ->fetch();
    }


    public function setSearch($action)
    {
        return TableFront::getInstance()
            ->setSearch(['type', '类型', 'select', \app\common\model\BonusPoolRecord::$_type]);
    }

    public function export(): Json
    {
        $s = $this->setMap($this->request->get('name'));

        $name = '分红池入池明细' . date('Y-m-d H:i:s');

        $title = TableFront::getInstance()->getFieldTable($this->request->get('name'));
        if (empty($title)) {
            return json(['code' => -1, 'msg' => '导出失败，请清除缓存后重试！']);
        }

        $s['filed'] = 'id,type,create_time,total_profit,profit_rate,amount';
        $list = $this->model::getSelect($s);

        return json(['code' => 1, 'result' => ['data' => $list['data']->toArray(), 'title' => $title, 'name' => $name]]);
    }

}
